/**
 * Created by json on 2016/8/18.
 */
var $ = $ || {};

$.OnLoginNativeObj = undefined;
$.OnLoginNative = function(data){
	if($.OnLoginNativeObj){
		//data
        //String zhongjiankey = "##";
        //userID+zhongjiankey+token+zhongjiankey+nickname+zhongjiankey+iconQzone+zhongjiankey+figureurl_qq_2
		
		//http://zjh.cjpoker.com/xlch/server/user.php
		//?action=setUserInfoEx&m_lUid=162019&m_sAccount=901B707964A5B3A914398A2033E897FE&m_sPassword=003AC88DA0A9E45005D85E03C9DA1575
		//&m_sAvatar=&m_sNickName=
		$.OnLoginNativeObj.OnLoginNative(data);
	}
};
$.isWXAppInstalled = function(data){
	if($.OnLoginNativeObj){
		if(data == "1"){
			$.OnLoginNativeObj.login_YOUKE.setVisible(false);
			$.OnLoginNativeObj.login_WX.setVisible(true);
		}else {
			$.OnLoginNativeObj.login_YOUKE.setVisible(true);
			$.OnLoginNativeObj.login_WX.setVisible(false);
		}
	}
};


dwc.LoginScene = cc.Scene.extend({
    sprite:null,
    ctor:function () {
        this._super();
        $.uid = 0;

        dwc.DT_Data_Login.InitData();

        $.is_FirstLogin = true;

        if(cc.sys.isNative)
        {
            cc.Device.setKeepScreenOn(true);
        }

        var that = this;

        $.disconnect_notice = 1;
        var mainNode=ccs.load(dwc.g_arrGCRes.loginMain_json).node;

        this.QQ_DATA = cc.sys.localStorage.getItem("QQ_DATA");
        this.WX_DATA = cc.sys.localStorage.getItem("WX_DATA");

        this.addChild(mainNode);
        this.initMain(mainNode);
		$.OnLoginNativeObj = this;

        this.loadRemoteSvrList();
        this.loadRes();

        if(dwc.DT_Data_Login.isConnected() == false)
        {
            var defaultWebsocketUrl = $.getItem("default_server_win");
            if(defaultWebsocketUrl)
            {
                dwc.DT_Data_Login.ConnectServer(defaultWebsocketUrl,function()
                {
                    that._detectServer(0);
                });
            }
        }

        this.schedule(this._connectServer,3.0);
        this.schedule(this._detectServer,1.0);

        dwc.DT_Data_Login.loadRemoteConfig();
        return true;
    },
    cntLoadRes : 0,
    loadRes : function()
    {
        var that = this;
        this.cntLoadRes = 0;
        var that = this;
        cc.loader.load(dwc.g_arrMJ4ResList, function () {

            for(var i=0;i<dwc.g_arrMJ4Plist.length;i++){
                var tmp = eval(dwc.g_arrMJ4Plist[i]);
                if(tmp){
                    cc.spriteFrameCache.addSpriteFrames(tmp);
                }
            }
            that.cntLoadRes++;
        }, that);
        /*cc.loader.load(dwc.g_arrZJHResList, function () {
            for(var i=0;i<dwc.g_arrZJHPlist.length;i++){
                var tmp = eval(dwc.g_arrZJHPlist[i]);
                if(tmp){
                    cc.spriteFrameCache.addSpriteFrames(tmp);
                }
            }
            that.cntLoadRes++;
        }, that);
        cc.loader.load(dwc.g_arrNNResList, function () {
            for(var i=0;i<dwc.g_arrNNPlist.length;i++){
                var tmp = eval(dwc.g_arrNNPlist[i]);
                if(tmp){
                    cc.spriteFrameCache.addSpriteFrames(tmp);
                }
            }
            that.cntLoadRes++;
        }, that);*/
    },
    loadRemoteSvrList : function()
    {
        if($.vecServerList.length > 0)
        {
            return;
        }
        var that = this;

        var bundleID = $.getBundleID();

        var gate_list = ["http://zjmj.cjpoker.com/app/server.php"];


        for(var i = 0;i < gate_list.length;i++)
        {
            try{
                var _domain = gate_list[i];
                var _url = _domain + "?bundle="+bundleID + "&os=ios";
                if(cc.sys.os == cc.sys.OS_ANDROID)
                {
                    var _url = _domain +  "?bundle="+bundleID + "&os=android";
                }
                if(cc.sys.os == cc.sys.OS_WINDOWS)
                {
                    var _url = _domain +  "?bundle="+bundleID + "&os=windows";
                }

                // 网络请求
                dwc.GX_NetWorkManager.SendMessage(_url,
                    function (_msg,_param) {
                        try {
                            that.message = JSON.parse(_msg);
                            var ips = that.message.ips_win;

                            if(ips) {
                                var vecIPs = ips.split("|");
                                $.vecServerList = [];
                                if (vecIPs.length >= 0)
                                {
                                    for (var i = 0 ;i < vecIPs.length;i++)
                                    {
                                        $.vecServerList[i] = "ws://" + vecIPs[i];
                                    }
                                    $.setItem("ips",ips);
                                }
                                if(dwc.DT_Data_Login.isConnected() == false)
                                {
                                    if($.vecServerList && $.vecServerList.length > 0)
                                    {
                                        for (var i = 0; i < $.vecServerList.length; i++) {
                                            dwc.DT_Data_Login.ConnectServer($.vecServerList[i],function()
                                            {
                                                that._detectServer(0);
                                            });
                                        }
                                    }
                                }
                            }
                        }catch (e)
                        {
                            cc.log(e.name + ":" + e.message);
                        }

                    },[_domain,_url]);
            }catch(e)
            {
                cc.log(e.name + ":" + e.message);
            }
        }
    },
    _connectServer : function(dt)
    {
    	var that = this;
        if(dwc.DT_Data_Login.isConnected() == false)
        {
            if($.vecServerList && $.vecServerList.length > 0)
            {
                for (var i = 0; i < $.vecServerList.length; i++) {
                    dwc.DT_Data_Login.ConnectServer($.vecServerList[i],function()
                    {
                        that._detectServer(0);
                    });
                }
            }else{
                this.loadRemoteSvrList();
            }
        }
    },
    _detectServer : function(dt)
    {
        var that = this;
        if(dwc.DT_Data_Login.isConnected() == true)
        {
            var bundle = $.getBundleID();
            if (bundle.startsWith("com.tongban.yisdk"))
            {
                this.OnYouKeLogin();
                this.unschedule(this._detectServer);
            }else{
                //判断是否安装微信
                try {
                    if (cc.sys.os == cc.sys.OS_ANDROID) {
                        jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "isWXAppInstalled", "(Ljava/lang/String;)V", "");
                        this.OnWXLogin();
                        this.unschedule(this._detectServer);
                    } else if (cc.sys.os == cc.sys.OS_IOS) {
                        if(this.WX_DATA && this.WX_DATA.length > 20) {
                            var installed = jsb.reflection.callStaticMethod("RootViewController", "isWXAppInstalled");
                            if (installed) {
                                this.OnWXLogin();
                                this.unschedule(this._detectServer);
                            }
                        }
                    }else{
                        this.OnYouKeLogin();
                        this.unschedule(this._detectServer);
                    }
                }catch (e)
                {
                    cc.log(e.name + ":" + e.message);
                }

            }
        }
    },
	
    initMain: function (mainNode) {
        var that=this;

        var login_YOUKE=  $.getNodeByName(mainNode,"ID_BUTTON_LOGIN_YOUKE");
        login_YOUKE.addClickEventListener(function () {that.OnYouKeLogin();});
		this.login_YOUKE = login_YOUKE;
        var login_WX=  $.getNodeByName(mainNode,"ID_BUTTON_LOGIN_WX");
        login_WX.addClickEventListener(function () {that.OnWXLogin();});
		this.login_WX = login_WX;
        this.showLoadingNode =  $.getNodeByName(mainNode,"ID_LAYOUT_LOADING");
        this.spLoading =  $.getNodeByName(mainNode,"ID_SPRITE_LOADING");
        this.spTouZi =  $.getNodeByName(mainNode,"ID_SPRITE_TOUZI");
        this.initLoadingEffect();
        this.ShowLoading(false);

        var logo = $.getNodeByName(mainNode,"ID_SPRITE_LOGO");
        var bundle = $.getBundleID();
        if(bundle == "com.cjpoker.xlch")
        {
            logo.initWithFile("res/image/logo_xlch.png");
        }
        if(bundle == "com.cjpoker.zujumj")
        {
            logo.initWithFile("res/image/logo_gdmj.png");
        }
        //判断是否安装微信
        try {
            if (cc.sys.os == cc.sys.OS_ANDROID) {
                jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "isWXAppInstalled", "(Ljava/lang/String;)V", "");
            } else if (cc.sys.os == cc.sys.OS_IOS) {
                var installed=  jsb.reflection.callStaticMethod("RootViewController", "isWXAppInstalled");
                if(installed){
                    login_YOUKE.setVisible(false);
                    login_WX.setVisible(true);
                }else {
                    login_YOUKE.setVisible(true);
                    login_WX.setVisible(false);
                }
            }
        }catch (e)
        {
            cc.log(e.name + ":" + e.message);
        }
    },
    initLoadingEffect : function()
    {
        this.spLoading.runAction(cc.repeatForever(cc.rotateBy(1.5,360)));
    },
    ShowLoading : function(visible)
    {
        var that = this;
        this.showLoadingNode.setVisible(visible);
        if(visible)
        {
            this.scheduleOnce(function(){
                that.ShowLoading(false);
            },5.0);
        }
    },
    OnYouKeLogin: function () {
        $.uid = 0;
        this.ShowLoading(true);
        /*
        if(dwc.DT_Data_Login.isConnected()) {
            dwc.DT_Data_Login.DoLogin(this.OnLoginSuccess);
        }


        var obj = {};
        obj.platform = "QQ";
        obj.userid = "GX123213123";
        obj.token = "XXXXXXXXX";
        obj.nickname = "同步";
        obj.usericon ="http://www.tongbanstudio.com/avatar/15.jpg";

        var platform = "QQ";
        platform = platform.toUpperCase();

        if(platform == "QQ" || platform.indexOf("QQ") >= 0) {
            dwc.DT_Data_Login.QQLogin(this.OnLoginSuccess, obj);
        }
        */
        this.unschedule(this._checkYouKeLogin);
        this.schedule(this._checkYouKeLogin,0.1);
        cc.audioEngine.playEffect("res/audio/pop.wav",false);
        return true;
    },
    _checkYouKeLogin : function(dt)
    {
        var that = this;
        //if(that.cntLoadRes<4)
		if(that.cntLoadRes<1)
        {
            return;
        }
		
        if(this.showLoadingNode.isVisible())
        {
            if(dwc.DT_Data_Login.isConnected())
            {
                dwc.DT_Data_Login.DoLogin(this.OnLoginSuccess);
                this.unschedule(this._checkYouKeLogin);
            }
        }else{
            this.unschedule(this._checkYouKeLogin);
        }
    },
    _checkQQLogin : function(dt)
    {
        var that = this;
        //if(that.cntLoadRes<4)
		if(that.cntLoadRes<1)
        {
            return;
        }
        if(this.showLoadingNode.isVisible())
        {
            if (dwc.DT_Data_Login.isConnected()) {
                this.unschedule(this._checkQQLogin);
                if(this.QQ_DATA && this.QQ_DATA.length > 20)
                {
                    var vecArg =  this.QQ_DATA.split("##");
                    var obj = {};
                    obj.platform = vecArg[0];
                    obj.userid = vecArg[1];
                    obj.token = vecArg[2];
                    obj.nickname = vecArg[3];
                    obj.usericon =vecArg[4];
                    obj.usergender =vecArg[5];
                    if(!obj.usergender)
                    {
                        obj.usergender = 0;
                    }

                    var platform = vecArg[0];
                    platform = platform.toUpperCase();

                    dwc.DT_Data_Login.QQLogin(this.OnLoginSuccess, obj);

                }else {
                    if (cc.sys.os == cc.sys.OS_ANDROID) {
                        jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "GoToLogin", "(Ljava/lang/String;)V", "qq");
                    } else if (cc.sys.os == cc.sys.OS_IOS) {
                        jsb.reflection.callStaticMethod("RootViewController", "OnQQLogin");
                    }
                }
            }
        }else{
            this.unschedule(this._checkQQLogin);
        }
    },
    _checkWXLogin : function(dt)
    {
        var that = this;
        //if(that.cntLoadRes<4)
		if(that.cntLoadRes<1)
        {
            return;
        }
        if(this.showLoadingNode.isVisible())
        {
            if(dwc.DT_Data_Login.isConnected())
            {
                this.unschedule(this._checkWXLogin);

                if(this.WX_DATA && this.WX_DATA.length > 20)
                {
                    var vecArg =  this.WX_DATA.split("##");
                    var obj = {};
                    obj.platform = vecArg[0];
                    obj.userid = vecArg[1];
                    obj.token = vecArg[2];
                    obj.nickname = vecArg[3];
                    obj.usericon =vecArg[4];
                    obj.usergender =vecArg[5];
                    if(!obj.usergender)
                    {
                        obj.usergender = 0;
                    }
                    obj.unionid = "";
                    if(vecArg[6])
                    {
                        obj.unionid = vecArg[6];
                    }
                    var platform = vecArg[0];
                    platform = platform.toUpperCase();

                    dwc.DT_Data_Login.WXLogin(this.OnLoginSuccess, obj);

                }else{
                    if (cc.sys.os == cc.sys.OS_ANDROID) {
                        jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "GoToLogin", "(Ljava/lang/String;)V", "wx");
                    } else if (cc.sys.os == cc.sys.OS_IOS) {
                        jsb.reflection.callStaticMethod("RootViewController",
                            "OnWXLogin");
                    }
                }
            }
        }else{
            this.unschedule(this._checkWXLogin);
        }
    },
    OnWXLogin: function () {
		
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            $.uid = 0;

            this.ShowLoading(true);

            this.schedule(this._checkWXLogin, 0.1);
        } else if (cc.sys.os == cc.sys.OS_IOS) {
            $.uid = 0;

            this.ShowLoading(true);

            this.schedule(this._checkWXLogin, 0.1);
        }else{
            this.OnYouKeLogin();
        }
        cc.audioEngine.playEffect("res/audio/pop.wav",false);
    },
    OnQQLogin: function () {
        $.uid = 0;

        this.ShowLoading(true);
        this.schedule(this._checkQQLogin,0.1);
            /*
            if (cc.sys.os == cc.sys.OS_ANDROID) {
                jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "GoToLogin", "(Ljava/lang/String;)V", "qq");
            } else if (cc.sys.os == cc.sys.OS_IOS) {
                jsb.reflection.callStaticMethod("RootViewController", "OnQQLogin");
            }
            */


        /*
        if(cc.sys.platform == cc.sys.DESKTOP_BROWSER ||cc.sys.platform == cc.sys.DESKTOP_BROWSER ) {
            var obj = {};
            obj.platform = "QQ";
            obj.userid = "GX123213123";
            obj.token = "XXXXXXXXX";
            obj.nickname = "同步";
            obj.usericon ="http://www.tongbanstudio.com/avatar/15.jpg";

            var platform = "QQ";
            platform = platform.toUpperCase();


            dwc.DT_Data_Login.QQLogin(this.OnLoginSuccess, obj);
        }
        */
        cc.audioEngine.playEffect("res/audio/pop.wav",false);
    },
    OnLoginSuccess: function () {

        $.setItem("default_server_win", $.defaultWebsocketUrl);
        cc.director.runScene(new dwc.DT_MainScene());
        //password=cc.sys.localStorage.getItem("Password");
        //device = cc.sys.localStorage.getItem("device");


    },
    OnLoginNative:function(data){
        data = decodeURIComponent(data);
        var vecArg =  data.split("##");

        //platform++userID++token++nickname++iconQzone++figureurl_qq_2


        var obj = {};
        obj.platform = vecArg[0];
        obj.userid = vecArg[1];
        obj.token = vecArg[2];
        obj.nickname = vecArg[3];
        obj.usericon =vecArg[4];
        obj.usergender =vecArg[5];
        if(!obj.usergender)
        {
            obj.usergender = 0;
        }
        obj.unionid = "";
        if(vecArg[6])
        {
            obj.unionid = vecArg[6];
        }

        cc.log("UNIONID:" + obj.unionid);

        var platform = vecArg[0];
        platform = platform.toUpperCase();

        if(platform == "QQ" || platform.indexOf("QQ") >= 0)
        {
            cc.sys.localStorage.setItem("QQ_DATA",data);
            dwc.DT_Data_Login.QQLogin(this.OnLoginSuccess,obj);
        }
        if(platform == "WX" || platform.indexOf("WX") >= 0 || platform.indexOf("WECHAT") >= 0)
        {
            cc.sys.localStorage.setItem("WX_DATA",data);
            dwc.DT_Data_Login.WXLogin(this.OnLoginSuccess,obj);
        }
    }

});
